package com.projet.whattowatch.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHandler extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;

	private static final String DATABASE_NAME = "BaseDeDonnee.sqlite";

	private Context mContext;
	private SQLiteDatabase mDataBase;

	public DataBaseHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.mContext = context;
	}

	public boolean databaseExist() {
		File dbFile = mContext.getDatabasePath(DATABASE_NAME);
		return dbFile.exists();
	}

	private void initDatabaseSpace() {
		getReadableDatabase();
		close();
		deleteDatabase();
	}

	public void deleteDatabase() {
		mContext.deleteDatabase(DATABASE_NAME);
	}

	public SQLiteDatabase open() throws SQLException {
		copy();
		mDataBase = SQLiteDatabase.openDatabase(getDatabasePath(), null,
				SQLiteDatabase.OPEN_READWRITE);
		return mDataBase;
	}

	private void copy() {
		if (!databaseExist()) {
			try {
				initDatabaseSpace();
				InputStream input = mContext.getAssets().open(DATABASE_NAME);
				FileOutputStream output = new FileOutputStream(
						getDatabasePath());
				byte[] buffer = new byte[1024];
				int length;
				while ((length = input.read(buffer)) > 0) {
					output.write(buffer, 0, length);
				}
				output.flush();
				output.close();
				input.close();
			} catch (IOException e) {
				Log.i("error copying database", e.toString());
				deleteDatabase();
			}
		}
	}

	private String getDatabasePath() {
		return mContext.getDatabasePath(DATABASE_NAME).getAbsolutePath();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

	public SQLiteDatabase getDatabase() {
		return mDataBase;
	}

	public void setDatabase(SQLiteDatabase database) {
		this.mDataBase = database;
	}
}